package liuyao.webutils.controller;

import liuyao.utils.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

@Controller
@RequestMapping("/network")
@CrossOrigin
public class NetworkController {

    @RequestMapping("/downloadFile/{fileName}")
    @ResponseBody
    public String downloadFile(@PathVariable String fileName,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        OutputStream os = null;
        InputStream is = null;
        try {
            String fileUrl = request.getQueryString();
            os = response.getOutputStream();
            URL url = new URL(fileUrl);
            URLConnection urlConn = url.openConnection();
            is = urlConn.getInputStream();
            int fileSize = urlConn.getContentLength();
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            if (fileSize > 0) {
                response.addHeader("Content-Length", "" + fileSize);
            }
            IOUtils.transferTo(is, os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            IOUtils.close(os, is);
        }
        return "ok";
    }
}
